<?php

/**
 * Created by PhpStorm.
 * User: william
 * Date: 16-8-30
 * Time: 下午2:15
 */
namespace V1;
class C_Home extends \ResourceClass
{
    public $isActive = true;
    public $remark = '用户端首页';

    public function get(array $req, array $post, &$result)
    {
        if (!isset($req['uid'])) {
            return 'require user id ';
        }
        if (!isset($req['userType'])) {
            return 'require user type';
        }
        if (!isset($req['k']) || !isset($req['t'])) {
            return 'data error';
        }
        if (!isset($req['enterpriseId'])) {
            return 'require enterprise id';
        }
        if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $req['enterpriseId'], $req['t'], $req['k']) == false) {
            return 'data illegal';
        }
        if (!isset($req['channelId'])) {
            return 'require channel id';
        }
        $l = isset($req['l']) ? $req['l'] : 20; //limit
        $o = isset($req['o']) ? $req['o'] : 0;  //offset
        $enterprise_id = $req['enterpriseId']; //获取企业id
        $channel_id = $req['channelId'];
        try {
            //获取商品列表
            $tabulation = new \Cls\Tabulation();
            $tabulation->setOffset($o);
            $tabulation->setLimit($l);
            $tabulation->setWhere('sell_status','=',\Cls\Product\Product::SELL_STATUS_PUTAWAY); // 取上架中的商品
            \Biz\ProductHandler::getProductListByEnterpriseIdAndChannelId($enterprise_id, $channel_id, $tabulation);
            $product_list = $tabulation->getData();
            if (!$tabulation->getSuccessStatus() || empty($product_list)) {
                $result['product_list'] = array();
            } else {
                // 获取当前渠道信息
                $channel_cls = \Biz\ChannelHandler::getChannelById($channel_id);
                $discount = $channel_cls->getDiscount();
                /**
                 * @var $product_cls \Cls\Product\Product
                 */
                foreach ($product_list as $product_cls) {
                    $product_cls_temp = new \stdClass();
                    $product_cls_temp->id = $product_cls->getId();
                    $product_cls_temp->enterprise_id = $product_cls->getEnterpriseId();
                    $product_cls_temp->brand_id = $product_cls->getBrandId();
                    $product_cls_temp->name = $product_cls->getName();
                    $product_cls_temp->icon_url = $product_cls->dealIconUrl();
                    $product_cls_temp->repertory_warning = $product_cls->getStockWarning();
                    $product_cls_temp->individual_packing = $product_cls->getSellUnitString();// 老版本
                    $product_cls_temp->mass_packing = $product_cls->getSellUnitString();  // 老版本
                    $product_cls_temp->sell_unit_string = $product_cls->getSellUnitString();
                    $product_cls_temp->remark = $product_cls->getDescription();
                    $product_cls_temp->insert_time = $product_cls->getCreateTime();
                    $product_cls_temp->is_del = $product_cls->getDelStatus();
                    $brand_cls = $product_cls->getBrandInfo();
                    if ($brand_cls instanceof \Cls\Brand\Brand) {
                        $brand_name = $brand_cls->getName();
                    } else {
                        $brand_name = '未知分类名称';
                    }
                    $product_cls_temp->brandname = $brand_name;
                    $product_channel_handler = new \Biz\ProductHandler();
                    $product_channel_cls=$product_channel_handler->getChannelProductByChannelIdAndProductId($channel_id,$product_cls->getId());
                    $channel_price = $product_channel_cls->getPriceRange();
                    if($channel_price !=false ){
                        $product_cls_temp->channel_price = (string)$channel_price;
                    }else{
                        $product_cls_temp->channel_price ='';
                    }
                    $product_cls_temp->collect_stock = $product_cls->getRepertoryTotal();
                    $product_cls_temp->stock_warning = $product_cls->judgeStockWaring();
                    $sku_list = $product_cls->getSkuList();
                    $product_cls_temp->sku_info = array();
                    if (!empty($sku_list)) {
                        /**
                         * @var $sku_cls \Cls\Product\Sku
                         */
                        foreach ($sku_list as $sku_cls) {
                            $sku_temp = new \stdClass();
                            $sku_temp->id = $sku_cls->getId();
                            $sku_temp->product_id = $sku_cls->getProductId();
                            $sku_temp->imgurl = $sku_cls->dealImageUrl();
                            $sku_temp->attr = $sku_cls->dealAttr();
                            $sku_temp->code = $sku_cls->getCode();
                            $sku_temp->sellprice = $sku_cls->getChannelSellingPrice($discount);
                            $sku_temp->cost = $sku_cls->getCost();
                            $sku_temp->stock = $sku_cls->getStock();
                            $sku_temp->insert_time = $sku_cls->getCreateTime();
                            $sku_temp->update_time = $sku_cls->getUpdateTime();
                            $product_cls_temp->sku_info [] = $sku_temp;
                        }
                    }
                    $result['product_list'][] = $product_cls_temp;
                }
            }

            /*
             *  促销活动信息
             *  ①筛选该企业下的所有有效活动
             *  ②在活动中筛选出用户所在渠道的活动，即活动的渠道为所有活动或者参与渠道中包含该渠道即可
             *  ③把满足条件的活动参与的产品与查询出的产品对应起来
             *  ④返回活动信息
             */
            $market_biz = new \Biz\MarketHandler();
            $tabulation = new \Cls\Tabulation();
            $tabulation->setLimit(99999);
            $tabulation->setWhere('enterprise_id', $enterprise_id);
            $time = date('Y-m-d H:i:s',time());
            $tabulation ->setWhere('end_time', '>', $time);
            $tabulation->setOrderBy('create_time','DESC');
            $market_biz->getListByEnterpriseId($tabulation);
            if ($tabulation->getSuccessStatus()) {
                $market_list = $tabulation->getData();
                //营销活动的渠道信息
                $market_biz->completeChannelListByMarketList($market_list);
                //完善营销活动中的商品信息
                $market_biz->completeProductListByMarketProductList($market_list);
                /**
                 * @var $market_cls \Cls\Market\Market
                 */
                foreach ($market_list as $market_cls) {
                    //如果活动参与的渠道类型是所有渠道或者当前用户所在的渠道在参与活动的渠道中
                    if ($market_cls->getChannelType() == \Cls\Market\Market::CHANNEL_ALL || $market_cls->judgeInChannel($channel_id)) {
                        //获取该活动参与的所有产品
                        $market_product_list = $market_cls->getProductList();
                        //取出所有产品的id组成id集合
                        $product_ids = array();
                        /**
                         * @var $market_product_cls \Cls\Market\Product
                         */
                        foreach ($market_product_list as $market_product_cls) {
                            $product_ids[] = $market_product_cls->getProductId();
                        }
                        //如果参与活动产品类型为所有产品或者该产品在参与的活动中

                        foreach ($result['product_list'] as $key => $product) {
                            $result['product_list'][$key]->activity_info = isset($result['product_list'][$key]->activity_info) ? $result['product_list'][$key]->activity_info : array();
                            if ($market_cls->getProductType() == \Cls\Market\Market::PRODUCT_ALL || in_array($product->id, $product_ids)) {
                                $market_cls_temp = new \stdClass();
                                $market_cls_temp->id = $market_cls->getId();
                                $market_cls_temp->title = $market_cls->getTitle();
                                $market_cls_temp->type = $market_cls->getType();
                                $market_cls_temp->condition = $market_cls->getCondition();
                                $market_cls_temp->discount = $market_cls->getDicount();
                                $market_cls_temp->rewards = $market_cls->getRewards();
                                $market_cls_temp->product_type = $market_cls->getProductType();
                                $market_cls_temp->channel_type = $market_cls->getChannelType();
                                $market_cls_temp->start_time = $market_cls->getStartTime();
                                $market_cls_temp->end_time = $market_cls->getEndTime();
                                $market_cls_temp->status = $market_cls->getStatus();
                                $market_cls_temp->enterprise_id = $market_cls->getEnterpriseId();
                                $market_cls_temp->unit = $market_cls->getUnit();
                                $market_cls_temp->create_time = $market_cls->getCreateAt();
                                $market_cls_temp->edit_time = $market_cls->getUpdateAt();
                                $market_cls_temp->update_time = $market_cls->getUpdateAt();
                                array_push($result['product_list'][$key]->activity_info, $market_cls_temp);
                            }
                        }
                    }
                }

                //计算折扣  按折扣活动的更新时间为键
                foreach ($result['product_list'] as $k => $product) {
                    if ((isset($product->activity_info)&&!empty($product->activity_info))) {
                        $new_activity = array();
                        foreach ($product->activity_info as $key => $activity) {
                            if ($activity->type == \Cls\Market\Market::TYPE_LOW_PRICE) { //只有活动类型为低价促时，才重新计算价格
                                $time = strtotime($activity->update_time);
                                $new_activity[$time] = $activity;
                                //因为后面需要重新筛选折扣活动，所以需要把原先的折扣活动删除
                                unset($result['product_list'][$k]->activity_info[$key]);
                            }
                        }
                        $new_activity = isset($new_activity) ? $new_activity : array();
                        krsort($new_activity);//把最新的折扣活动放前面
                        $sort_activity = current($new_activity);//取出最终满足的活动
                        if(!empty($sort_activity)) {
                            foreach($product->sku_info as $ke => $sku_cls){
                                $product->sku_info[$ke]->sellprice = round($sku_cls->sellprice*$sort_activity->discount,2);
                            }
                            array_push($result['product_list'][$k]->activity_info,$sort_activity);
                        }
                    }else{
                        $result['product_list'][$k]->activity_info = array();
                    }
                    $activity_info = array_merge($result['product_list'][$k]->activity_info);
                    $result['product_list'][$k]->activity_info = $activity_info;
                }
            } else {
                foreach ($result['product_list'] as $key => $product) {
                    $result['product_list'][$key]->activity_info = array();
                }
            }
            $tabulation = new \Cls\Tabulation();
            $tabulation->setLimit(99999);
            $tabulation->setWhere('is_hot', \Cls\Brand\Brand::IS_HOT);
            $brand_list = \Biz\BrandHandler::getAllBrandListByEnterpriseId($enterprise_id, $tabulation);
            if(!empty($brand_list)){ //此数据已不用
                \Biz\BrandHandler::setImagesInfo($brand_list);
                /**
                 * @var $brand_cls \Cls\Brand\Brand
                 */
                foreach ($brand_list as $brand_cls) {
                    $result['hot_brand_list'][] = array(
                        'id' => $brand_cls->getId(),
                        'icon' => $brand_cls->dealRestIconUrl(),
                        'title' => $brand_cls->getName(),
                    );
                }
            } else { //为空时也要有
                $result['hot_brand_list'][] = array(
                    'id' => 0,
                    'icon' => '',
                    'title' => '',
                );
            }
            $result['middle_function_area'] = array(
                array(
                    'id' => 1,
                    'title' => '企业风采',
                    'icon_url' => 'http://image.freshqiao.com/files/qiye-icon.png',
                    'action' => array(
                        'id' => '6',
                        'name' => '企业风采',
                    ),
                ),
                array(
                    'id' => 2,
                    'title' => '新品上架',
                    'icon_url' => 'http://image.freshqiao.com/files/xinpin-icon.png',
                    'action' => array(
                        'id' => '7',
                        'name' => '新品上架',
                    ),
                ),
                array(
                    'id' => 3,
                    'title' => '我的收藏',
                    'icon_url' => 'http://image.freshqiao.com/files/shoucang-icon.png',
                    'action' => array(
                        'id' => '8',
                        'name' => '我的收藏',
                    ),
                ),
                array(
                    'id' => 4,
                    'title' => '最近购买',
                    'icon_url' => 'http://image.freshqiao.com/files/goumai-icon.png',
                    'action' => array(
                        'id' => '9',
                        'name' => '最近购买',
                    ),
                ),
                array(
                    'id' => 5,
                    'title' => '所有商品',
                    'icon_url' => 'http://image.freshqiao.com/files/quanbu-icon.png',
                    'action' => array(
                        'id' => '10',
                        'name' => '全部商品',
                    ),
                ),
            );
            /*
             * 获取广告位
             * $type =4 广告位
             * */
            $market_biz = new \Biz\MarketHandler();
            $tabulation = new \Cls\Tabulation();
            $tabulation->setLimit(99999);
            $market_biz->getAdvertisementOrHotsiteByEnterpriseId($enterprise_id, $tabulation);
            $advertiseInfo = array();
            $advertisement_list = $tabulation->getData();
            if ($tabulation->getSuccessStatus() === true && !empty($advertisement_list)) {
                $advertiseData = array();
                /**
                 * @var $market_section \Cls\Market\Section
                 */

                foreach ($advertisement_list as $market_section) {
                    $market_section_list = $market_section->getAdvertisementAndPromotionList();
                    if (!empty($market_section_list)) {
                        /**
                         * @var $market_actionPara \Cls\Market\Actionpara
                         */
                        $section_type = $market_section->getSectionType();
                        if ($section_type != \Cls\Market\Section::SECTION_ADVERTISEMENT) {
                            continue;
                        }
                        foreach ($market_section_list as $market_actionPara) {
                            $para_value = $market_actionPara->getParaValue();
                                $data = array(
                                    'id' => $market_section->getId(),
                                    'title' => $market_section->getTitle(),
                                    'icon_url' => $market_section->getIcon(),
                                    'action_id' => $market_actionPara->getActionId(),
                                    'action_name' => $market_actionPara->getActionName(),
                                    'para_value' => $para_value,
                                );
                                $advertiseInfo[] = self::getByActionId($data);
                        }
                    }
                }
            } else {
                $advertiseInfo = array(
                    array(
                        "id" => "1",
                        "title" => "鲜桥默认广告1",
                        "icon_url" => "http://image.freshqiao.com/files/default_ad.png",
                        "action" => array(
                            "id" => "5",
                            "name" => "无动作",
                        )
                    ),
                    array(
                        "id" => "2",
                        "title" => "鲜桥默认广告2",
                        "icon_url" => "http://image.freshqiao.com/files/default_ad2.png",
                        "action" => array(
                            "id" => "5",
                            "name" => "无动作",
                        )
                    ),
                );
            }
            if(empty($advertiseInfo)){
                $advertiseInfo = array(
                    array(
                        "id" => "1",
                        "title" => "鲜桥默认广告1",
                        "icon_url" => "http://image.freshqiao.com/files/default_ad.png",
                        "action" => array(
                            "id" => "5",
                            "name" => "无动作",
                        )
                    ),
                    array(
                        "id" => "2",
                        "title" => "鲜桥默认广告2",
                        "icon_url" => "http://image.freshqiao.com/files/default_ad2.png",
                        "action" => array(
                            "id" => "5",
                            "name" => "无动作",
                        )
                    ),
                );
            }
            $result['advertise_list'] = $advertiseInfo;
            $promotionInfo = array();
            /*
             * 获取促销位
             * $type = 5 广告促销位
             * */
            if ($tabulation->getSuccessStatus() === true && !empty($advertisement_list)) {
                /**
                 * @var $market_section \Cls\Market\Section
                 */
                foreach ($tabulation->getData() as $market_section) {
                    $market_section_list = $market_section->getAdvertisementAndPromotionList();
                    if (!empty($market_section_list)) {
                    }
                    $section_type = $market_section->getSectionType();
                    if ($section_type != \Cls\Market\Section::SECTION_PROMOTION) {
                        continue;
                    }
                    $i = 0;
                    foreach ($market_section_list as $market_actionPara) {
                        $para_value = $market_actionPara->getParaValue();
                            $i++;
                            if ($i <= 3) {  //返回三条促销广告
                                $data = array();
                                $data = array(
                                    'id' => $market_section->getId(),
                                    'title' => $market_section->getTitle(),
                                    'icon_url' => $market_section->getIcon(),
                                    'action_id' => $market_actionPara->getActionId(),
                                    'action_name' => $market_actionPara->getActionName(),
                                    'para_value' => $para_value,
                                );
                                $promotionInfo[] = self::getByActionId($data);
                            } else {
                                break;
                            }
                    }
                }

            }
            $result['promotion_list'] = $promotionInfo;
        } catch (Exception $e) {
            return $e->getMessage();
        }
        return '';
    }

    /**
     * @param $market_actionPara
     * @return array|null
     */
    protected static function  getByActionId($data)
    {
        if (empty($data))
            return null;
        if ($data['action_id'] == 2) {
            $data_info = array(
                'id' => $data['id'],
                'title' => $data['title'],
                'icon_url' => $data['icon_url'],
                'action' => array(
                    'id' => $data['action_id'],
                    'name' => $data['action_name'],
                    'parameter' => array(
                        'title' => '',
                        'url' => $data['para_value'],
                    ),

                ),
            );
        } else if ($data['action_id'] == 3) {
            $data_info = array(
                'id' => $data['id'],
                'title' => $data['title'],
                'icon_url' => $data['icon_url'],
                'action' => array(
                    'id' => $data['action_id'],
                    'name' => $data['action_name'],
                    'parameter' => array(
                        'title' => '',
                        'shopId' => '',
                        'productId' => $data['para_value'],
                        'productName' => '',
                        'productPrice' => '',
                        'productSpec' => '',
                        'productRemark' => ''

                    ),

                ),
            );
        } else if ($data['action_id'] == 4) {
            $data_info = array(
                'id' => $data['id'],
                'title' => $data['title'],
                'icon_url' => $data['icon_url'],
                'action' => array(
                    'id' => $data['action_id'],
                    'name' => $data['action_name'],
                    'parameter' => array(
                        'title' => '',
                        'brandId' => $data['para_value'],
                    ),

                ),
            );
        } else {
            $data_info = array(
                'id' => $data['id'],
                'title' => $data['title'],
                'icon_url' => $data['icon_url'],
                'action' => array(
                    'id' => $data['action_id'],
                    'name' => $data['action_name'],
                    'parameter' => array(
                        'title' => '',
                    ),

                ),
            );
        }
        return $data_info;
    }
}